﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;


namespace 项目
{
    class DBHelper
    {
        //数据库连接字符串
       public static string connString = "server=.;database=Supermarket;Integrated Security=true";
        //数据库连接对象
        public static SqlConnection conn = null;
        //初始化数据库连接
        public static void InitConnection()
        {
            //如果连接对象不存在，则创建连接
            if (conn==null)
            
               conn = new SqlConnection(connString);
            //如果连接对象关闭则创建连接
            if (conn.State == ConnectionState.Closed) ;
            conn.Open();
            //如果连接中断则重启连接
            if (conn.State == ConnectionState.Broken)
                conn.Close();
                conn.Open();
        }
        //查询，获取DataReader
        public static SqlDataReader GetDataReader(string sql) 
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql, conn);
            //当DataReader对象被关闭时，自动关闭占用的连接对象
            return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            
        }
        //增删改操作
        public static bool ExcuteNonQuery(string sql)
        {
            bool result = false;
            InitConnection();
            //创建链接
            SqlCommand cmd = new SqlCommand(sql, conn);
            int num = cmd.ExecuteNonQuery();            
            if (num>0)
            {
                result = true;

            }
            return result;
        }

    }
}
